package com.demo.demo.itext7.page;

import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import java.io.IOException;
import java.net.MalformedURLException;


public class HeaderEventHandler implements IEventHandler {

  /*  private Image image;

    public HeaderEventHandler(Image image) {
        this.image = image;
    }*/

    public void handleEvent(Event event) {
        PdfFont font2 = null;
        try {
            font2 = PdfFontFactory.createFont("D:\\font\\MYingHei.ttf", PdfEncodings.IDENTITY_H, false);

        } catch (IOException e) {
            e.printStackTrace();
        }
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdf = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        int pageNumber = pdf.getPageNumber(page);
        if(pageNumber==1){//第一页不需要设置页眉
            return;
        }
        Rectangle pageSize = page.getPageSize();

        PdfCanvas pdfCanvas = new PdfCanvas(
                page.getLastContentStream(), page.getResources(), pdf);
        Canvas canvas = new Canvas(pdfCanvas, pdf, pageSize);
        Image image = null;
        try {

            image = new Image(ImageDataFactory.create("D:\\output-onlineimagetools.jpg"));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        float x =  pageSize.getLeft()+60;
        float y =  pageSize.getTop()-40;
        float x2 =  pageSize.getRight()-100;
        float y2 =  pageSize.getTop()-35;

        image.scaleAbsolute(160f,21f);
        image.setFixedPosition(pageSize.getLeft()+30,y);
        canvas.add(image);
        canvas.setFontSize(8f);

        try {
//            Paragraph p =  new Paragraph();
//            p.setFont(font2);
//            p.add("left");
//            canvas.showTextAligned(p, x, y, TextAlignment.CENTER);


            Paragraph p2 =  new Paragraph();
            p2.setFont(font2);
            p2.add("Date 日期: 2022-02-02\n");
            p2.add("Page No ⾴數: " + pageNumber);
            canvas.showTextAligned(p2, x2, y2, TextAlignment.LEFT);

            canvas.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
